<template>
	<view class="container">
		<u-form :model="form" ref="uForm">
			<u-form-item prop="goodsName">
				<u-input v-model="form.goodsName" :clearable="false" maxlength="30" placeholder="宝贝名称" />
			</u-form-item>
			
			<u-form-item prop="description">
				<u-input 
					v-model="form.description" 
					type="textarea" 
					:border="false"
					maxlength=140
					:auto-height="false"
					:clearable="false"
					placeholder="描述一下你要卖的宝贝吧(使用感受,入手渠道,转手原因...)" />
			</u-form-item>
			
			<u-form-item>
				<u-upload 
					:action="action" 
					:header="header" 
					:file-list="fileList" 
					name="file" 
					@on-uploaded="uploaded"
					ref="uUpload" 
					:auto-upload="false" 
					max-count="3"
					:limitType="limitType"
					:size-type="sizeType"
					:show-progress="false">
				</u-upload>
			</u-form-item>
			
			<u-form-item label="收取方式" prop="sendType" label-width="150">
				<u-radio-group v-model="form.sendType" @change="radioGroupChange($event)">
					<u-radio 
						shape="circle" 
						v-for="(item, index) in sendTypeList" 
						:key="index" 
						:name="item.dictValue">{{ item.dictLabel }}</u-radio>
				</u-radio-group>
			</u-form-item>
			
			<u-form-item label="自取地址" prop="address"  label-width="150" v-if="form.sendType == 1">
				<u-input type="text" v-model="form.address" placeholder="例: 4栋501"/>
			</u-form-item>
			
			<u-form-item label="所属分类" prop="category" label-width="150">
				<u-input type="select" v-model="category" placeholder="请选择分类" @click="cateGorySelectShow = true"></u-input>
				<u-select 
					mode="mutil-column-auto" 
					:safe-area-inset-bottom="true"
					v-model="cateGorySelectShow" 
					:list="cateGoryList" 
					value-name="id" 
					label-name="label" 
					@confirm="categoryConfirm"
				></u-select>
			</u-form-item>
			
			<u-row>
				<u-col span="6">
					<u-form-item label="价格 ￥" prop="price" label-width="120">
						<u-input type="number" maxlength="5" v-model="form.price" placeholder="0.00"/>
					</u-form-item>
				</u-col>
				<u-col span="6">
					<u-form-item label="入手价 ￥" prop="oriPrice" label-width="140">
						<u-input type="number" maxlength="5" v-model="form.oriPrice" placeholder="入手价(选填)"/>
					</u-form-item>
				</u-col>
			</u-row>
			
			<u-button  type="error" shape="circle" :loading="loading" @click="submit">发布</u-button>
			
			
			<u-toast ref="uToast" />
		</u-form>
		
		<view class="bottom"></view>
	</view>
</template>

<script>
	import {appConfig} from '@/config/config.js'
	import {constant} from '@/utils/constant.js'
	import {
		getTreeselect
	} from "@/api/category.js";
	import {
		publish,getGoodsInfo
	} from "@/api/goods.js";
	import {
		getDicts
	} from "@/api/dict-data.js";
	export default {
		data() {
			return {
				form: {
					goodsId: undefined,
					goodsName: '',
					description: '',
					picsArray: [],
					sendType: 1,
					address: '',
					categoryId: 0,
					price: '',
					oriPrice: ''
				},
				action: appConfig.WEB_API + '/common/upload',
				header: {
					'Content-Type': 'application/json',
					'ApiAuthorization': uni.getStorageSync(constant.tokenKey)
				},
				fileList: [],  // 图片回显列表
				limitType: ['png', 'jpg', 'jpeg', 'webp', 'gif'], // 图片格式限制
				sizeType: ['compressed'], // 图片压缩
				category: '',  // 分类框显示字符串
				sendTypeList: [],  // 收取方式列表
				cateGorySelectShow: false,   // 选择分类显示标识
				cateGoryList: [],            // 分类树列表
				loading: false,
				rules: {
					goodsName: [{ 
						required: true, 
						message: '宝贝名称不能为空',
						trigger: ['change','blur']
					}],
					description: [{ 
						required: true, 
						message: '写点什么吧',
						trigger: ['change','blur']
					}],
					address: [{ 
						required: true, 
						message: '请填写地址',
						trigger: ['change','blur']
					}]
				}
			}
		},
		methods: {
			// 选中任一 radio时，由radio-group触发
			radioGroupChange(e) {
				this.form.sendType = e
			},
			// 选择分类回调
			categoryConfirm(e) {
				const labels = e.map(item => {
					return item.label
				})
				this.category = labels.join("/")
				this.form.categoryId = e[e.length - 1].value
				console.log(this.form.categoryId)
			},
			getGoodsInfo(goodsId) {
				getGoodsInfo(goodsId).then(res => {
					this.form = res.data
					// 图片回显
					this.fileList = res.data.picsArray.map(item => {
						return {url: item}
					})
					// 分类回显
					this.cateGoryList.forEach(level1 => {
						if(level1.id == this.form.categoryId) {
							this.category = level1.label
						} else if (level1.children) {
							level1.children.forEach(level2 => {
								if(level2.id == this.form.categoryId) {
									this.category = level1.label + '/' + level2.label
								}
							})
						}
					})
				})
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						// 地址校验
						if (this.form.categoryId == 0) {
							this.$refs.uToast.show({
								title: '请选择分类',
								type: 'warning'
							})
						} else if (this.form.price == '') {
							this.$refs.uToast.show({
								title: '请输入价格',
								type: 'warning'
							})
						} else {
							// 发布按钮点击才进行图片上传
							this.$refs.uUpload.upload();
						}
						
					}
				});
			},
			// 所有图片上传完毕触发
			uploaded(lists, name){
				console.log(lists)
				console.log(name)
				
				if (lists.length != 0) {
					this.loading = true
					this.form.picsArray = lists.map(item => {
						if (item.response) {
							return item.response.data.url
						} else {
							return item.url
						}
						
					})
					
					publish(this.form).then(res => {
						this.$u.route({
							url: '/pages/goods-detail/goods-detail',
							type: 'redirectTo',
							params: {
								goodsId: res.data.goodsId
							}
						})
					})
					this.loading = false
				} else {
					this.$refs.uToast.show({
						title: '请上传宝贝图片',
						type: 'warning'
					})
				}
			}
		},
		// 表单校验：必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onShow() {
			
		},
		async onLoad(options) {
			
			// 查询字典：商品收取类型
			await getDicts('hy_goods_send_type').then(res => {
				this.sendTypeList = res.data
			})
			
			// 查询分类树进行同步操作
			await getTreeselect().then(res => {  
				this.cateGoryList = res.data
			})
			
			if (options.goodsId) {
				this.getGoodsInfo(options.goodsId)
			}
			
		}
	}
</script>

<style lang="scss">
	@import "./add-goods.scss";
</style>
